/* AddressBar.java
 * Author: liuex
 * 2007-12-22 ����02:33:04
 *
 * Note: 
 */
package lex.explorer.address;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JTextField;

import org.lex.catalog.CatalogEvent;
import org.lex.explorer.FileInfo;
import org.lex.explorer.model.DefaultFileSystemModel;
import org.lex.explorer.model.FileSystemModel;
import org.lex.io.IO;
import org.lex.swing.SelectAllWhenGainFocus;
import org.lex.utils.SystemProperties;

import lex.explorer.IExplorer;

public class AddressBar extends JTextField implements IExplorer {
	private FileSystemModel fileModel = null;

	public AddressBar() {
		this(new File(SystemProperties.userHome()));
	}

	public AddressBar(String dir) {
		this(new File(dir));
	}

	public AddressBar(File directory) {
		this(new DefaultFileSystemModel(directory));
	}

	public AddressBar(FileSystemModel model) {
		this.initialize();
		this.setFileModel(model);
	}

	public FileSystemModel getFileModel() {
		return fileModel;
	}

	public void setFileModel(FileSystemModel model) {
		if (null != this.fileModel)
			this.fileModel.removeCatalogListener(this);
		this.fileModel = model;
		this.fileModel.addCatalogListener(this);
		this.catalogChanged(new CatalogEvent(model, model.getCatalog()));
	}

	public void catalogChanged(CatalogEvent e) {
		this.setText(IO.getCanonicalPath(getFileModel().getCatalog().getFile()));
		// this.setText( getFileModel().getCatalog().getSource().toString() );
	}

	private void initialize() {
		this.addFocusListener(SelectAllWhenGainFocus.getInstance());
		this.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String text = getText().trim();
				File file = new File(text);
				if (file.exists() && file.isDirectory())
					fileModel.setCatalog(FileInfo.get(fileModel.getFileView(), file));
			}
		});
	}
}
